package com.ruoyi.project.system.controller;

import java.util.List;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.LoginUser;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.domain.SysOrganize;
import com.ruoyi.project.system.service.ISysOrganizeService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 组织机构Controller
 * 
 * @author frank
 * @date 2024-08-26
 */
@RestController
@RequestMapping("/system/organize")
public class SysOrganizeController extends BaseController
{
    @Autowired
    private ISysOrganizeService sysOrganizeService;

    /**
     * 查询组织机构列表
     */
    @PreAuthorize("@ss.hasPermi('system:organize:list')")
    @GetMapping("/list")
    public AjaxResult list(SysOrganize sysOrganize)
    {
        List<SysOrganize> list = sysOrganizeService.selectSysOrganizeList(sysOrganize);
        return success(list);
    }

    /**
     * 导出组织机构列表
     */
    @PreAuthorize("@ss.hasPermi('system:organize:export')")
    @Log(title = "组织机构", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysOrganize sysOrganize)
    {
        List<SysOrganize> list = sysOrganizeService.selectSysOrganizeList(sysOrganize);
        ExcelUtil<SysOrganize> util = new ExcelUtil<SysOrganize>(SysOrganize.class);
        util.exportExcel(response, list, "组织机构数据");
    }

    /**
     * 获取组织机构详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:organize:query')")
    @GetMapping(value = "/{organizeId}")
    public AjaxResult getInfo(@PathVariable("organizeId") String organizeId)
    {
        return success(sysOrganizeService.selectSysOrganizeByOrganizeId(organizeId));
    }

    /**
     * 新增组织机构
     */
    @PreAuthorize("@ss.hasPermi('system:organize:add')")
    @Log(title = "组织机构", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysOrganize sysOrganize)
    {
        if (!sysOrganizeService.checkOrganizeNameUnique(sysOrganize))
        {
            return error("新增组织失败，编号或名称已存在");
        }
        LoginUser loginUser = getLoginUser();
        String organizeId = getOrganizeId();
        sysOrganize.setSysCreatedby(getUserId().toString());
        if(!SecurityUtils.isAdmin(getUserId())){
            SysOrganize organize = sysOrganizeService.selectSysOrganizeByOrganizeId(getOrganizeId());
            sysOrganize.setSysOrg(organize.getOrgFlg().equals(1)?organize.getOrganizeId():organize.getParentId());
            sysOrganize.setSysDivision(organize.getOrganizeId());
//            sysOrganize.setSysPostn();
        }
        return toAjax(sysOrganizeService.insertSysOrganize(sysOrganize));
    }

    /**
     * 修改组织机构
     */
    @PreAuthorize("@ss.hasPermi('system:organize:edit')")
    @Log(title = "组织机构", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysOrganize sysOrganize)
    {
        String organizeId = sysOrganize.getOrganizeId();
        sysOrganizeService.checkOrganizeDataScope(organizeId);
        if (!sysOrganizeService.checkOrganizeNameUnique(sysOrganize))
        {
            return error("修改组织信息失败，编号或者名称已存在");
        }
        else if (sysOrganize.getParentId().equals(organizeId))
        {
            return error("修改组织信息失败，上级部门不能是自己");
        }
//        else if (StringUtils.equals(UserConstants.ORGANIZE_DISABLE, sysOrganize.getActiveFlag().toString())
//                && sysOrganizeService.selectNormalChildrenOrById(deptId) > 0)
//        {
//            return error("该部门包含未停用的子部门！");
//        }
        sysOrganize.setSysLastUpdBy(getUserId().toString());
        return toAjax(sysOrganizeService.updateSysOrganize(sysOrganize));
    }

    /**
     * 删除组织机构
     */
    @PreAuthorize("@ss.hasPermi('system:organize:remove')")
    @Log(title = "组织机构", businessType = BusinessType.DELETE)
	@DeleteMapping("/{organizeId}")
    public AjaxResult remove(@PathVariable String organizeId)
    {
        if (sysOrganizeService.hasChildByOrganizeId(organizeId))
        {
            return warn("存在下级组织,不允许删除");
        }
        if (sysOrganizeService.checkOrganizeExistUser(organizeId))
        {
            return warn("存在用户,不允许删除");
        }
        sysOrganizeService.checkOrganizeDataScope(organizeId);
        return toAjax(sysOrganizeService.deleteSysOrganizeByOrganizeId(organizeId));
    }
}
